import { Tool, ToolColor } from '../../../Tool';

/**
 * 面积测量
 */
export class AreaTool extends Tool {
	constructor(viewer, options = {}, ...args) {
		super(arguments);
		this.viewer = viewer;
		this.options = options;
		this.float = options?.float ?? 2;

		this.clickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		this.handler = new Cesium.MeasureHandler(
			this.viewer,
			Cesium.MeasureMode.Area,
			Cesium.ClampMode.Space
		);
		this.handler.lineColor = Cesium.Color.fromCssColorString(ToolColor.functionalColor);
		this.handler.fillColor = Cesium.Color.fromCssColorString(
			ToolColor.toRgba(ToolColor.functionalColor, 0.3)
		);
		viewer.scene.layers.layerQueue.forEach((item) => {
			item.selectEnabled = false;
			item.releaseSelection();
		});
		[...arguments].forEach((item) => {
			if (typeof item === 'function') {
				this.callback = item;
			}
		});
		this.callbackValue = {
			total: null,
			current: null,
			tool: this
		};
	}

	start() {
		let areaStr = '';
		let count = 0;
		this.clickHandler.setInputAction((e) => {
			++count;
			if (count > 2) {
				this.callbackValue.current = areaStr;
				this.callback && this.callback(this.callbackValue);
			}
		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

		this.handler.measureEvt.addEventListener((result) => {
			const area = Number(result.area);
			areaStr =
				area > 1000000
					? (area / 1000000).toFixed(this.float) + 'km²'
					: area.toFixed(this.float) + '㎡';

			const textEntity = this.handler.areaLabel;
			textEntity.text = '面积:' + areaStr;
			textEntity.font = '14px sans-serif';
			textEntity.showBackground = true;
			textEntity.backgroundColor = Cesium.Color.fromCssColorString(
				ToolColor.toRgba(ToolColor.backgroundColor, 0.8)
			);
			textEntity.fillColor = Cesium.Color.fromCssColorString(ToolColor.color);
			textEntity.style = Cesium.LabelStyle.FILL;
			textEntity.disableDepthTestDistance = Number.POSITIVE_INFINITY;
			// this.handler.polygon.polygon.material = new Cesium.Color(0.2, 0.53, 1, 0.2)
		});

		this.handler.activeEvt.addEventListener((isActive) => {
			if (isActive === true) {
				this.viewer.enableCursorStyle = true;
				this.viewer._element.style.cursor = 'Crosshair';
			} else {
				count = 0;
				this.viewer.enableCursorStyle = false;
				this.viewer._element.style.cursor = '';
			}
		});
		this.handler.activate();
	}

	cancel() {
		this.clickHandler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
		this.handler.clear();
		this.handler.deactivate();
	}
}
AreaTool.toolId = 'AreaTool';
